<?php
include_once('config/config.php');
$auth = !empty($_COOKIE['auth']) ? json_decode($_COOKIE['auth'],true):[];
// 判断变量是否为空
if(!empty($auth))
{
    showMsg('您已登录了，无须重复登录','index.php');
}


// 判断是否有POST请求
if ($_POST) {
    // 接收参数
    $username=trim($_POST['username']) ?? '';
    $password=trim($_POST['password']) ?? '';
    $code=trim($_POST['code']) ?? '';
    
    // 判断参数是否为空
    if (empty($username)) {
        showMsg('用户名不能为空');
    }
    if (empty($password)) {
        showMsg('密码不能为空');
    }
    if (empty($code)) {
        showMsg('验证码不能为空');
    }
    // 比较验证码与输入的值
    if ($_SESSION['code'] != $code) {
        showMsg('验证码错误');
    }
    // 查询数据库是否有该用户名（管理员）
    $adminSql="SELECT * FROM `pre_admin` WHERE `username` = '$username'";
    $admin = find($adminSql);
    if (!$admin) {
        showMsg('管理员不存在');
    }
    $password = md5($password . $admin['salt']);
    if ($password != $admin['password']) {
        showMsg('密码错误');
    }
    $data=[
        'id'=>$admin['id'],
        'username'=>$admin['username']
    ];
    // 设置cookie
    setcookie('auth',json_encode($data));
    showMsg('登录成功','index.php');
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php include_once('common/meta.php'); ?>

    <script src="lib/jquery-1.7.2.min.js" type="text/javascript"></script>
</head>

<body>
    <div class="navbar">
        <div class="navbar-inner">
            <a class="brand" href="index.html"><span class="second">Admin</span></a>
        </div>
    </div>

    <div class="row-fluid">
        <div class="dialog">
            <div class="block">
                <p class="block-heading">登录</p>
                <div class="block-body">
                    <form method="post">
                        <label>用户名</label>
                        <input type="text" name="username" class="span12">
                        <label>密码</label>
                        <input type="password" name="password" class="span12">
                        <label>验证码</label>
                        <div>
                            <input type="text" name="code" id="code" class="span9">
                            <img src="./config/imgcode.php" onclick="this.src = '/config/imgcode.php?id='+Math.random()" alt="">
                        </div>
                        <button class="btn btn-primary pull-right">登录</button>
                        <div class="clearfix"></div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>

</html>
<?php include_once('common/script.php'); ?>